<!--
  功能：功能描述
  作者：kangjie
  邮箱：kangjie@briup.com
  时间：2021年12月20日 15:13:54
  版本：v1.0
  修改记录：
  修改内容：
  修改人员：
  修改时间：
-->
<template>
  <div class="infomessge">
    <!-- 资讯分类 -->
    <div class="header">
      <el-row>
        <!-- <el-button color="#626aef" style="color: white">Custom</el-button> -->
         <el-button type="text" @click="back">返回</el-button>
        <el-button color="#626aef" plain @click="addInfo">发布文章</el-button>
        <input type="text" v-model="input">
        <el-button  style="background-color: #409EFF ;color:#FFF" plain @click="search">搜索</el-button>
      </el-row>

      <div class="tableContent">
        <el-table :data="my_infos" style="width: 100%" v-loading="loading">
            <el-table-column label="图片"  width="180" align="center">
          <template slot-scope="scope">
            <el-image style="width: 100px; height: 100px" :src="scope.row.cover" @load="imgFinish"
              :preview-src-list="[scope.row.cover]">
              <div slot="placeholder" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
          </template>
        </el-table-column>

        <el-table-column prop="title" label="标题" width="250" align="center">
           <template slot-scope="scope">
             <div>{{scope.row.title}}</div>
          <div  >
            <span style="color:#909399;font-size:10px;text-align:center" > 
              {{scope.row.name}}
              </span>
          </div>
           </template>
        </el-table-column>

      

        <el-table-column  label="状态" width="180" align="center">
          <template slot-scope="scope">

            <div v-if="scope.row.status=='审核通过'">
              <el-tag type="success">{{scope.row.status}}</el-tag> 
              </div>  
            <div v-else >
               <el-tag type="danger">{{scope.row.status}} </el-tag> 
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <!-- <el-button @click="handleClick(scope.row)" type="text" size="small">查看</el-button> -->
            <el-button type="text" size="small" @click="delInfo(scope.row.id)">删除</el-button>
            <el-button type="text" size="small" @click="editInfo(scope.row)">编辑</el-button>
            <el-button type="text" size="small" @click="goToDetails(scope.row)">查看详情</el-button>
          </template>
        </el-table-column> 
      </el-table>

    <!-- 模态框 -->
       <el-dialog :title="dialogTitile" :visible.sync="infoVisible" width="80%" :before-close="handleClose">
      <el-form :model="infoForm"  label-width="100px" class="demo-ruleForm" ref="InfoFormRef">
        <!-- 表单项 -->
        <!-- 名称 -->
        <el-form-item label="标题" prop="title">
          <el-input v-model="infoForm.title"></el-input>
        </el-form-item>
        <!-- 头像 -->
        <el-form-item label="头像：">
          <el-upload
            class="avatar-uploader"
            :action="uploadFileURL"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
            style="width: 100px; height: 100px"
              v-if="imageUrl"
              :src="imageUrl"
              class="avatar"
            >
            <i v-else class="el-icon-plus avatar-uploader-icon" />
             <div slot="tip" class="el-upload__tip">文件大小不允许超过3M</div>
          </el-upload>
        </el-form-item>
           <el-form-item label="正文" prop="content">
      //编辑器的使用
        <Tinymce v-model="infoForm.content" :height="100" :width="800" />
      </el-form-item>

       <el-form-item>
        <el-button type="primary" @click="onSubmit">{{sub2}}</el-button>
      </el-form-item>
      </el-form>
        
    </el-dialog>

    </div>
    </div>

  </div>
</template>

<script>
  import {
    mapActions,
    mapMutations,
    mapState,
    getters
  } from 'vuex'
  import {
    get,
    post,
  } from '@/utils/request'
  import request from "@/utils/request";
import { log } from '@antv/g2plot/lib/utils';
import qs from "querystring";
import Tinymce from "@/components/Tinymce";
import { mapGetters } from "vuex";
export default {
  // 组件名称
  name: "demo",
  // 组件参数 接收来自父组件的数据
  props: {},
 
  // 组件状态值
  data() {
    return {
       // 文件预览的路径     文件预览路径+文件id
        showFileURL: 'http://121.199.29.84:8888/group1/',
        // 项目基础路径和文件上传路径
        uploadFileURL: 'http://121.199.29.84:8001/file/upload',
        infoForm:{},
      input:'',
      title:'',
      loading: false,
      infoVisible:false,
      imageUrl:'',
      dialogTitile:'头像修改',
      imgFace:'',
      sub2:''
    };
  },
  // 计算属性
  computed: {
    ...mapState('info',['infos',' infoCatogory']),
    ...mapGetters('info',['my_infos'])
  },
  // 注册组件
  components:{
     Tinymce 
  },
  // 侦听器
  watch: {},
  // 组件方法
  methods: {
    ...mapActions('info', ['getInfoVuex','getInfoCatogoryVuex']),
    ...mapMutations('info',['FIND_ARTICLE_BY_TITLE',]),

    goToDetails(item){
      console.log(item)
      //路由传值
       this.$router.push({ path: '/info/Details', query: { item }} )
    },

    getInfo(){
      // this.loading = true
      this.getInfoVuex()
    },
       //删除产品
      delInfo(id) {
        // console.log(id)
        this.$confirm('确认删除？')
          //确认按钮事件
          .then(_ => {
            get('/article/deleteById', {
              id: id
            }).then(res => {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.getInfo()
            })
          })
          // 取消按钮事件
          .catch(_ => {});

      },
       imgFinish() {
        this.loading = false;
      },
      search(){
          if(this.input.length == 0){
            this.getInfo();
          }else{
            this.FIND_ARTICLE_BY_TITLE(this.input.trim())
          }
      },
       editInfo(proObj) {
         this.sub2='保存'
        this.infoForm = {
          ...proObj
        };
        this.imageUrl = this.infoForm.cover;
        this.dialogTitile = '编辑文本';
        this.infoVisible = true
      },
      
      handleClose() {
        // 清空表单的数据 和 验证信息
        this.$confirm('确认关闭？')
          //确认按钮事件
          .then(_ => {
            this.infoVisible = false
            done();
          })
          // 取消按钮事件
          .catch(_ => {});
      },
       // 保存修改
      submitForm() {
        this.$refs['InfoFormRef'].validate((valid) => {
          if (valid) {
          //  console.log(this.productForm)
            this.infoVisible = false;
            post("/article/saveOrUpdate", 
              this.infoForm).then(res => {
              if (res.status == 200) {
                this.$message({
                  title: '成功',
                  message: res.message,
                  type: 'success'
                });
                // this.getProductData()
                this.loading = false
                this.infoVisible = false
              } else {
                this.$message({
                  title: '失败',
                  message: res.message,
                  type: 'danger'
                });
              }

            })

          } else {
             console.log('error submit!!');
            return false;
          }
        });
      },
       back() {
      this.$router.go(-1);
    },
    // 图片上传之前做的处理
      handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
        // this.infoForm.cover = this.showFileURL + res.data.id;
        this.infoForm.cover = this.showFileURL + res.data.id;

      },
      // 图片上传之前做的处理
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt3M = file.size / 1024 / 1024 < 3;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt3M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt3M;
      },
      // 发布文章
      onSubmit() {
      // this.infoForm.authorId = this.infos.id; //用户
      // this.infoForm.categoryId = 3; //风采
      this.infoVisible = true
      this.$refs['InfoFormRef'].validate((valid) => {
        if (valid) {
          // 交互
          request
            .request({
              url: "/article/saveOrUpdate",
              method: "post",
              headers: {
                "Content-Type": "application/x-www-form-urlencoded",
              },
              data: qs.stringify(this.infoForm),
            })
            .then((response) => {
              // 提示成功
              this.$message({ message: response.message, type: "success" });
              // 返回列表页
            //  this.back();
            this.infoVisible = false
             this.getInfo();
            });
        } else {
          return false;
        }
      });
    },
    addInfo(){
       this.infoForm = {}
       this.sub2='发布'
        this.dialogTitile = '新增产品信息'
        this.imageUrl = '';
        this.infoVisible = true
    }

  },
  // 以下是生命周期钩子
  /**
   * 组件实例创建完成，属性已绑定，但DOM还未生成，$ el属性还不存在
   */
  created() {
    this.getInfo();
    this.getInfoCatogoryVuex();
  },
  /**
   * el 被新创建的 vm.$ el 替换，并挂载到实例上去之后调用该钩子。
   * 如果 root 实例挂载了一个文档内元素，当 mounted 被调用时 vm.$ el 也在文档内。
   */
  mounted() {},
  /**
   * 实例销毁之前调用。在这一步，实例仍然完全可用。
   */
  beforeDestroy() {},
  /**
   * Vue 实例销毁后调用。调用后，Vue 实例指示的所有东西都会解绑定，
   * 所有的事件监听器会被移除，所有的子实例也会被销毁。
   */
  destroyed() {},
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<!--使用了scoped属性之后，父组件的style样式将不会渗透到子组件中，-->
<!--然而子组件的根节点元素会同时被设置了scoped的父css样式和设置了scoped的子css样式影响，-->
<!--这么设计的目的是父组件可以对子组件根元素进行布局。-->
<style scoped>
</style>
